package com.spring.security.study.security_test.handler;


import com.spring.security.study.security_test.api.SysUserDetails;
import com.spring.security.study.security_test.api.TokenEntry;
import com.spring.security.study.security_test.utils.TokenUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : UserLoginSuccessHandler
 * @Author : lby
 * @Date: 2021/1/25 17:19
 * @Description :
 */
@Component
@Slf4j
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    /**
     * 当用户成功通过身份验证时调用
     *
     * @param request  导致成功身份验证的请求
     * @param response 响应
     * @throws IOException      抛异常
     * @throws ServletException 抛异常
     */
    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 组装JWT
        SysUserDetails user =  (SysUserDetails) authentication.getPrincipal();
        String token = TokenUtils.createToken(user);
        token = TokenEntry.TOKEN_PREFIX + token;
        // 封装返回参数
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("userInfo",user);
        resultData.put("code", "200");
        resultData.put("msg", "登录成功");
        resultData.put("token", token);
        log.info("数据:{}",resultData);
//        JsonResultT.responseJson(response, resultData);

    }
}
